package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service

public class AddressBookImpl implements AddressBookService {

    @Autowired
    AddressBookMapper addressBookMapper;
    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void save(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        //默认不设置成默认地址
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    /**
     * 获取用户的地址簿
     */
    @Override
    public List<AddressBook> getUserAddressBook() {
        //获取用户的 userId
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> addressBookList =  addressBookMapper.getAddressBookByUserId(userId);
        return addressBookList;
    }

    @Override
    public void updateDefaultAddress(Long id) {
        //默认地址只能有一个
        //先将所有地址的is_default设置为 0 再将id对应的地址值设置为 1
        Long userId = BaseContext.getCurrentId();
        addressBookMapper.updateDefaultTo0(userId);
        //获取当前用户id
        addressBookMapper.updateDefaultTo1(id);

    }

    @Override
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookMapper.getByAddressId(id);
        return addressBook;
    }

    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    @Override
    public AddressBook getDefaultAddress() {
        AddressBook addressBook = addressBookMapper.getDefaultAddress();
        return addressBook;
    }


}
